<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>ArrayBuffer 在canvas中的应用</h1>
<canvas id="canvas" width="400" height="300"></canvas>
<h1>ArrayBuffer 在 FileReader 中的应用</h1>
选择一个文件：<input id="fileInput" type="file">

<script>
  const canvas = document.getElementById('canvas');
  const ctx = canvas.getContext('2d');
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const uint8ClampedArray = imageData.data;

  // 打印数据
  console.log('uint8ClampedArray: => ', uint8ClampedArray)
</script>

<script>
  const $fileInput = document.getElementById('fileInput');

  $fileInput.addEventListener('change', function () {
    const file = fileInput.files[0];
    const reader = new FileReader();

    /// TODO 1、对图片数据做一些处理。
    reader.readAsArrayBuffer(file);
    reader.onload = function () {
      const img = new Image();
      const arrayBuffer = reader.result;

      /// TODO 2、对图片数据做一些处理。

      /// TODO 3、最后渲染到canvas
      img.onload = function() {
        // 将图片写入 canvas 画布
        ctx.drawImage(img, 0, 0, 400, 300);
      }
      img.src = 'data:image/jpeg;base64,'+ arrayBufferToBase64(arrayBuffer);

      // ArrayBuffer(){}
      console.log('FileReader: => ', arrayBuffer);
    };
  }, false);

  function arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  }
</script>
</body>
</html>
